package net.csdn.business.mirror.utils;

import com.csvreader.CsvReader;
import com.google.common.collect.Lists;
import net.csdn.business.mirror.entity.bo.csv.CsvFileInfo;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CsvUtil {
    public static CsvFileInfo readCSVFile(InputStream inputStream) throws Exception {
        CsvFileInfo csvFileInfo = new CsvFileInfo();
        CsvReader reader = new CsvReader(inputStream, ',', Charset.defaultCharset());

        reader.readHeaders();
        String[] headers = reader.getHeaders();

        if (headers == null) {
            throw new Exception("csv 头部解析失败");
        }

        Map<Integer, String[]> rows = new HashMap<>();
        int i = 1;
        while (reader.readRecord()) {
            ++i;
            String[] rowData = new String[headers.length];
            for (int j = 0; j < headers.length; j++) {
                rowData[j] = reader.get(headers[j]);
            }
            rows.put(i, rowData);
        }
        reader.close();

        csvFileInfo.setHeaders(headers);
        csvFileInfo.setRows(rows);
        return csvFileInfo;
    }

    public static List<String[]> getData(InputStream inputStream) throws Exception {
        CsvFileInfo csvFileInfo = readCSVFile(inputStream);
        List result = Lists.newArrayList();
        for (Map.Entry<Integer, String[]> integerEntry : csvFileInfo.getRows().entrySet()) {
            String[] values = integerEntry.getValue();
            result.add(values);
        }
        return result;
    }
}
